﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Andz.Tool.URLBuilder.Properties;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using XrmToolBox;

namespace Andz.Tool.URLBuilder
{
    public partial class UrlBuilder : PluginBase 
    {
        public UrlBuilder()
        {
            InitializeComponent();
        }

        public override Image PluginLogo
        {
            get { return Resources.Logo; }
        }

        private void PopulateEntityList()
        {
            if (Service != null)
            {
                WorkAsync("Loading Entity List...", (w, e) =>
                {
                    // query entity metadata
                    var retrieveRequest = new RetrieveAllEntitiesRequest
                    {
                        EntityFilters = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };
                    var response = (RetrieveAllEntitiesResponse)Service.Execute(retrieveRequest);
                    var entityNames = new List<string>();
                    if (response.EntityMetadata != null)
                    {
                        entityNames.AddRange(response.EntityMetadata.OrderBy(entity => entity.LogicalName).Select(entity => entity.LogicalName));
                    }
                    else
                    {
                        entityNames.Add("There is no Entity Available.");
                    }
                    e.Result = entityNames;
                }, 
                e => { EntityNameDdl.DataSource = e.Result; }, 
                e => { });
            }
        }

        private void GenerateButton_Click(object sender, EventArgs e)
        {
            if (EntityNameDdl.SelectedText != "There is no Entity Available." &&
                !String.IsNullOrEmpty(RecordGuidTextBox.Text))
            {
                var protocol = (ConnectionDetail.UseSsl ? "https" : "http");
                var baseUrl = string.Empty;
                if (ConnectionDetail.UseOnline || ConnectionDetail.UseOsdp)
                {
                    baseUrl = ConnectionDetail.OrganizationUrlName + "." + ConnectionDetail.ServerName;
                }
                else if (ConnectionDetail.UseIfd)
                {
                    // TODO: check the base URL for IFD
                    baseUrl = ConnectionDetail.ServerName; //ConnectionDetail.Organization + "." + 
                }
                else
                {
                    //TODO: check the base URL for OnPremise
                    baseUrl = ConnectionDetail.ServerName +
                              (!String.IsNullOrEmpty(ConnectionDetail.ServerPort)
                                  ? ":" + ConnectionDetail.ServerPort
                                  : "") +
                              "/" + ConnectionDetail.Organization;
                }
                GeneratedUrlTextBox.Text = String.Format("{0}://{1}/main.aspx?etn={2}&pagetype=entityrecord&id={3}", protocol, baseUrl, EntityNameDdl.SelectedValue, RecordGuidTextBox.Text);
            }
            else
            {
                MessageBox.Show("Incomplete parameter required for the operation to complete.");
            }
        }
        
        private void OpenButton_Click(object sender, EventArgs e)
        {
            var sInfo = new ProcessStartInfo(GeneratedUrlTextBox.Text);
            Process.Start(sInfo);
        }

        private void UrlBuilder_Load(object sender, EventArgs e)
        {
            PopulateEntityList();
        }
    }
}
